<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use app\common\model\TeacherAudit as TeacherAuditModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;


/**
 * 教师
 *
 * @icon fa fa-circle-o
 */
class Teacher extends Backend
{

    /**
     * Teacher模型对象
     * @var \app\common\model\Teacher
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Teacher;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user','audit'])
            ->where($where)
            ->where([
                'teacher.deletetime' => Db::raw('teacher.deletetime is null'),
            ])
            ->order($sort, $order)
            ->paginate($limit);
        $TeacherAuditModel = new TeacherAuditModel();
        foreach ($list as &$vo) {
            $find = $TeacherAuditModel->where([
                'user_id' => $vo['user_id'],
                'status' => 1
            ])->find();
            if ($find) {
                $vo['need_audit'] = 1;
            }else{
                $vo['need_audit'] = 0;
            }
            $vo['order_count'] = Db::name('teacher_order')->where(['teacher_id' => $vo['user_id']])->count();
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $TeacherAudit = new TeacherAuditModel();
        $with = $TeacherAudit->order('id desc')->where([
            'user_id'=>$row['user_id'],
            'status'=>2
        ])->find();
        $this->assign('with',$with);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if(isset($params['teacher_age']) && $params['teacher_age']===''){
                $params['teacher_age'] = null;
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function updateWeigh()
    {
        // 获取传递的 ID 和 weigh 值
        $id = input('post.id');
        $weigh = input('post.weigh');

        // 更新数据库中的 weigh 字段
        $result = Db::name('teacher')->where('user_id', $id)->update(['weigh' => $weigh]);

        if ($result !== false) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }

    public function redis_export()
    {
        $params = $this->request->post();
        if(isset($params['export_ids']) && $params['export_ids']){
            session('export_ids',$params['export_ids']);
            $this->success('缓存成功');
        }else{
            $this->error('导出失败');
        }
    }

    public function export()
    {
        ini_set('memory_limit', '1024M');
        $params = $this->request->get();

        $where = [
            'deletetime' => null
        ];

        //导出页面选择的数据
        if(!isset($params['data'])){
            $export_ids = session('export_ids');
            $where['user_id'] = ['in',$export_ids];
        }
//        print_r($where);
//        die;

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $lists = $this->model->where($where)->select();

        $sheet->getStyle('A1:D7')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->getColumnDimension('A')->setWidth(20);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('C')->setWidth(20);
        $sheet->getColumnDimension('D')->setWidth(20);
        $sheet->getColumnDimension('E')->setWidth(30);
        $sheet->getColumnDimension('F')->setWidth(30);
        $sheet->getColumnDimension('G')->setWidth(20);
        $sheet->getColumnDimension('H')->setWidth(20);
        $sheet->getColumnDimension('I')->setWidth(20);
        $sheet->getColumnDimension('J')->setWidth(20);
        $sheet->getColumnDimension('K')->setWidth(20);
        $sheet->getColumnDimension('L')->setWidth(20);
        $sheet->getColumnDimension('M')->setWidth(20);
        $sheet->getColumnDimension('N')->setWidth(20);
        $sheet->getColumnDimension('O')->setWidth(30);
        $sheet->getColumnDimension('P')->setWidth(30);
        $sheet->getColumnDimension('Q')->setWidth(20);
        $sheet->getColumnDimension('R')->setWidth(20);
        $sheet->getColumnDimension('S')->setWidth(20);
        $sheet->getColumnDimension('T')->setWidth(20);
        $sheet->getColumnDimension('U')->setWidth(20);
        $sheet->getColumnDimension('V')->setWidth(20);
        $sheet->getColumnDimension('W')->setWidth(20);
        $sheet->getColumnDimension('X')->setWidth(20);
        $sheet->getColumnDimension('Y')->setWidth(20);
        $sheet->getColumnDimension('Z')->setWidth(20);
        $sheet->getColumnDimension('AA')->setWidth(20);
        $sheet->getColumnDimension('AB')->setWidth(20);
        $sheet->getColumnDimension('AC')->setWidth(20);
        $sheet->getColumnDimension('AD')->setWidth(40);
        $sheet->getColumnDimension('AE')->setWidth(40);
        $sheet->getColumnDimension('AF')->setWidth(20);
        $sheet->getColumnDimension('AG')->setWidth(40);
        $sheet->getColumnDimension('AH')->setWidth(20);

        // 设置一些数据到单元格
        $sheet->getRowDimension(1)->setRowHeight(26);
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '真实姓名');
        $sheet->setCellValue('C1', '头像');
        $sheet->setCellValue('D1', '星级');
        $sheet->setCellValue('E1', '授课方式');
        $sheet->setCellValue('F1', '免费入驻类型');
        $sheet->setCellValue('G1', '付费入驻类型');
        $sheet->setCellValue('H1', '昵称');
        $sheet->setCellValue('I1', '联系方式');
        $sheet->setCellValue('J1', '微信手机号');
        $sheet->setCellValue('K1', '身份证号');
        $sheet->setCellValue('L1', '性别');
        $sheet->setCellValue('M1', '身份证正面');
        $sheet->setCellValue('N1', '身份证反面');
        $sheet->setCellValue('O1', '学生证/校园卡/毕业证书');
        $sheet->setCellValue('P1', '手持学生证/校园卡/毕业证书');
        $sheet->setCellValue('Q1', '院校名称');
        $sheet->setCellValue('R1', '学历开始时间');
        $sheet->setCellValue('S1', '学历结束时间');
        $sheet->setCellValue('T1', '学历');
        $sheet->setCellValue('U1', '专业');
        $sheet->setCellValue('V1', '年级');
        $sheet->setCellValue('W1', '主辅教');
        $sheet->setCellValue('X1', '寒暑假授课区域');
        $sheet->setCellValue('Y1', '非寒暑假授课区域');
        $sheet->setCellValue('Z1', '教龄');
        $sheet->setCellValue('AA1', '个人标签');
        $sheet->setCellValue('AB1', '教师资格证');
        $sheet->setCellValue('AC1', '职称证书');
        $sheet->setCellValue('AD1', '教育经历');
        $sheet->setCellValue('AE1', '成功案例');
        $sheet->setCellValue('AF1', '奖励荣誉');
        $sheet->setCellValue('AG1', '个人照片');
        $sheet->setCellValue('AH1', '是否为名师');


        $teacherAuditModel = new TeacherAuditModel();
        for($i=0;$i<count($lists);$i++){
            $audit = $teacherAuditModel->where([
                'user_id' => $lists[$i]['user_id'],
                'status' => 2
            ])->order('id desc')->find();
            $sheet->getRowDimension($i+2)->setRowHeight(100);
            $sheet->setCellValue('A'.($i+2),$lists[$i]['user_id']);
            $sheet->setCellValue('B'.($i+2),$lists[$i]['realname']);


            if($lists[$i]['avatar']) {
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH . 'public' . $lists[$i]['avatar']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('C' . ($i + 2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            $sheet->setCellValue('D'.($i+2),$lists[$i]['star'].'星');
            $sheet->setCellValue('E'.($i+2),$audit['teaching_method']);
            $sheet->setCellValue('F'.($i+2),$audit['settled_type_free']);
            $sheet->setCellValue('G'.($i+2),$audit['settled_type']);
            $sheet->setCellValue('H'.($i+2),$audit['nickname']);
            $sheet->setCellValue('I'.($i+2),$audit['mobile']);
            $sheet->setCellValue('J'.($i+2),$audit['wx_phone']);
            $sheet->setCellValue('K'.($i+2),$audit['id_code']);
            $sheet->setCellValue('L'.($i+2),$audit['sex']);

            if($audit['id_card_front']){
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH.'public'.$audit['id_card_front']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('M'.($i+2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            if($audit['id_card_reverse']) {
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH . 'public' . $audit['id_card_reverse']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('N' . ($i + 2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            if($audit['school_image']) {
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH . 'public' . $audit['school_image']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('O' . ($i + 2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            if($audit['school_image_hand']) {
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH . 'public' . $audit['school_image_hand']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('P' . ($i + 2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            $sheet->setCellValue('Q'.($i+2),$audit['school_name']);
            $sheet->setCellValue('R'.($i+2),$audit['learn_start']);
            $sheet->setCellValue('S'.($i+2),$audit['learn_end']);
            $sheet->setCellValue('T'.($i+2),$audit['education']);
            $sheet->setCellValue('U'.($i+2),$audit['profession']);
            $sheet->setCellValue('V'.($i+2),$audit['grade']);

            // 启用单元格自动换行（运行换行）
            $sheet->getStyle('W'.($i+2))->getAlignment()->setWrapText(true);

            $give_lessons = json_decode($audit['give_lessons'],true);
            $give_lessons_str = '主教:'.$give_lessons[0]['grade_cn'].'-'.$give_lessons[0]['subject_cn'];
            if(isset($give_lessons[1]) && $give_lessons[1]['grade_cn']){
                $give_lessons_str .= "\r\n".'辅教:'.$give_lessons[1]['grade_cn'].'-'.$give_lessons[1]['subject_cn'];
            }
            $sheet->setCellValue('W'.($i+2),$give_lessons_str);


            $holiday_area = explode(',',$audit['holiday_area']);
            $holiday_area_str = '';
            // 启用单元格自动换行（运行换行）
            $sheet->getStyle('X' . ($i + 2))->getAlignment()->setWrapText(true);
            foreach($holiday_area as $k=>$v){
                if ($k > 0) {
                    $holiday_area_str .= "\r\n";
                }
                $holiday_area_str .= $v;
            }
            $sheet->setCellValue('X'.($i+2),$holiday_area_str);


            $unholiday_area = explode(',',$audit['unholiday_area']);
            $unholiday_area_str = '';
            // 启用单元格自动换行（运行换行）
            $sheet->getStyle('Y' . ($i + 2))->getAlignment()->setWrapText(true);
            foreach($unholiday_area as $k=>$v){
                if ($k > 0) {
                    $unholiday_area_str .= "\r\n";
                }
                $unholiday_area_str .= $v;
            }
            $sheet->setCellValue('Y'.($i+2),$unholiday_area_str);


            $sheet->setCellValue('Z'.($i+2),$audit['teacher_age']);
            $sheet->setCellValue('AA'.($i+2),$audit['tags']);

            if($audit['main_image']) {
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH . 'public' . $audit['main_image']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('AB' . ($i + 2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            if($audit['cert_image']) {
                $drawing = new Drawing();
                $drawing->setName($lists[$i]['realname'])
                    ->setDescription($lists[$i]['realname'])
                    ->setPath(ROOT_PATH . 'public' . $audit['cert_image']) // 图片路径
                    ->setHeight(100) // 设置图片的高度（可根据需要调整）
                    ->setCoordinates('AC' . ($i + 2)) // 图片放入B2单元格
                    ->setOffsetY(15)
                    ->setWorksheet($sheet); // 将图片添加到工作表中
            }

            if($audit['teacher_exp']) {
                // 启用单元格自动换行（运行换行）
                $sheet->getStyle('AD' . ($i + 2))->getAlignment()->setWrapText(true);
                $teacher_exp = json_decode($audit['teacher_exp'], true);
                $teacher_exp_str = '';
                foreach ($teacher_exp as $key => $val) {
                    if ($key > 0) {
                        $teacher_exp_str .= "\r\n";
                    }
                    $teacher_exp_str .= $val['start'] . '~' . $val['end'] . ':' . $val['content'];
                }
                $sheet->setCellValue('AD' . ($i + 2), $teacher_exp_str);
            }

            if($audit['case_name'] && $audit['case_content']){
                // 启用单元格自动换行（运行换行）
                $sheet->getStyle('AE'.($i+2))->getAlignment()->setWrapText(true);
                $cases = $audit['case_name'].'\r\n'.$audit['case_content'];
                $sheet->setCellValue('AE'.($i+2),$cases);
            }

            if($audit['honor_images']) {
                $honor_images = explode(',', $audit['honor_images']);
                foreach ($honor_images as $key => $val) {
                    $drawing = new Drawing();
                    $drawing->setName($lists[$i]['realname'])
                        ->setDescription($lists[$i]['realname'])
                        ->setPath(ROOT_PATH . 'public' . $val) // 图片路径
                        ->setHeight(100) // 设置图片的高度（可根据需要调整）
                        ->setCoordinates('AF' . ($i + 2)) // 图片放入B2单元格
                        ->setOffsetY(15)
                        ->setWorksheet($sheet); // 将图片添加到工作表中
                }
            }

            if($audit['photo_images']) {
                $photo_images = explode(',', $audit['photo_images']);
                foreach ($photo_images as $key => $val) {
                    $drawing = new Drawing();
                    $drawing->setName($lists[$i]['realname'])
                        ->setDescription($lists[$i]['realname'])
                        ->setPath(ROOT_PATH . 'public' . $val) // 图片路径
                        ->setHeight(100) // 设置图片的高度（可根据需要调整）
                        ->setCoordinates('AG' . ($i + 2)) // 图片放入B2单元格
                        ->setOffsetY(15)
                        ->setOffsetX(40 * $key)
                        ->setWorksheet($sheet); // 将图片添加到工作表中
                }
            }

            if($lists[$i]['recommend']){
                $sheet->setCellValue('AH'.($i+2),'是');
            }


        }



        // 设置响应头，以便浏览器下载文件
        $writer = new Xls($spreadsheet);
        $filename=date("Y-m-d").'_全体教师.xls';
        $writer->save($filename);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
        ob_clean();
        flush();
        readfile($filename);//输出文件;
    }

}
